package org.alvin.locknew;

import javax.websocket.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
@ClientEndpoint
public class LockClient {

    private static String uri = "ws://127.0.0.1:80/ws";
    private static Session session;

    public void connect() {
        WebSocketContainer container = null;
        try {
            container = ContainerProvider.getWebSocketContainer();
            try {
                URI r = URI.create(uri);
                session = container.connectToServer(this, r);
            } catch (DeploymentException | IOException e) {
                e.printStackTrace();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("error: " + ex);
        }

    }

    public void send(String msg) throws IOException {
        session.getBasicRemote().sendText(msg);
    }

    public static void main(String[] args) {
        LockClient client = new LockClient();
        client.connect();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = "";
        try {
            do {
                input = br.readLine();
                if (!input.equals("exit")) {
                    client.send("java client: " + input);
                }
            } while (!input.equals("exit"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @OnOpen
    public void onOpen(Session session) {
        System.out.println("已连接，请输入要发送的信息：");
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("Client收到的消息: " + message);
    }

    @OnClose
    public void onClose() {
        System.out.println("关闭");
    }
}


